import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import type { User } from '../types/api'

interface UserState {
  user: User | null
  token: string | null
  isLoggedIn: boolean
}

interface UserActions {
  setUser: (user: User) => void
  setToken: (token: string) => void
  login: (user: User, token: string) => void
  logout: () => void
  updateUser: (userData: Partial<User>) => void
}

export const useUserStore = create<UserState & UserActions>()(
  persist(
    (set, get) => ({
      user: null,
      token: null,
      isLoggedIn: false,

      setUser: (user) => set({ user, isLoggedIn: true }),

      setToken: (token) => set({ token }),

      login: (user, token) => set({
        user,
        token,
        isLoggedIn: true
      }),

      logout: () => set({
        user: null,
        token: null,
        isLoggedIn: false
      }),

      updateUser: (userData) => {
        const currentUser = get().user
        if (currentUser) {
          set({
            user: { ...currentUser, ...userData }
          })
        }
      }
    }),
    {
      name: 'user-storage'
    }
  )
)

export default useUserStore